package com.song.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.rabbitmq.client.Channel;
import com.song.common.exception.NoStockException;
import com.song.common.to.mq.OrderTo;
import com.song.common.to.mq.StockDetailTo;
import com.song.common.to.mq.StockLockedTo;
import com.song.common.utils.R;
import com.song.mall.ware.entity.WareOrderTaskDetailEntity;
import com.song.mall.ware.entity.WareOrderTaskEntity;
import com.song.mall.ware.feign.OrderFeignService;
import com.song.mall.ware.feign.ProductFeignService;
import com.song.mall.ware.service.WareOrderTaskDetailService;
import com.song.mall.ware.service.WareOrderTaskService;
import com.song.mall.ware.vo.*;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.song.common.utils.PageUtils;
import com.song.common.utils.Query;

import com.song.mall.ware.dao.WareSkuDao;
import com.song.mall.ware.entity.WareSkuEntity;
import com.song.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;




@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService orderTaskService;

    @Autowired
    WareOrderTaskDetailService orderTaskDetailService;



    @Autowired
    RabbitTemplate rabbitTemplate;



    @Autowired
    OrderFeignService orderFeignService;


    /**
     * 解锁功能
     * @param to
     * @param message
     */
    /*@RabbitHandler
    public void handleStockRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        *//**
         * 1、查询数据库关于这个订单的锁定库存的信息
         * 有：证明库存锁定成功了
         *   解锁：订单情况
         *     1、没有这个订单 无需解锁
         *     2、有这个订单。
         *          订单状态：已取消：解锁库存
         *                   没取消：不能解锁
         * 没有：库存锁定失败了 库存回滚 无需解锁
         *//*
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId!=null){
            //解锁
            Long id = to.getId();
            //查到订单信息
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            //通过订单信息得到订单号
            String orderSn = taskEntity.getOrderSn();
            //根据订单号 查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                //订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                //订单不存在
                //判断订单状态 4:订单已被取消了
                if (data==null||data.getStatus() == 4 ){
                    //解锁
                    unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
                }else{
                    //消息拒绝以后 重新放到队列当中   让别人继续消费解锁
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
                }
            }
        }else{
            //无需解锁
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }*/

    private void unLockStock(Long skuId,Long wareId,Integer num,Long taskDetailId){
        //解锁
        wareSkuDao.unLockStock(skuId,wareId,num);
        //更新库存工作单的状态
        WareOrderTaskDetailEntity entity = new WareOrderTaskDetailEntity();
        entity.setId(taskDetailId);
        entity.setLockStatus(2);//已解锁
        orderTaskDetailService.updateById(entity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId).eq("sku_num", skuNum));
        if (entities==null||entities.size()==0){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStockLocked(0);
            //TODO 远程查询 sku的name
            //TODO 还可以让异常不回滚 高级部分
            try {
                R info = productFeignService.info(skuId);
                if (info.getCode()==0){
                    Map<String,Object> data = (Map<String, Object>) info.get("data");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            wareSkuDao.insert(wareSkuEntity);
        }
        wareSkuDao.addStock(skuId,wareId,skuNum);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skusId) {

        List<SkuHasStockVo> collect = skusId.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku总库存量
            Long  count = baseMapper.getSkuStock(skuId);

            vo.setSkuId(skuId);
            vo.setHasStock(count==null?false:count>0);

            return vo;
        }).collect(Collectors.toList());
        return collect;
    }

    @Transactional(rollbackFor = NoStockException.class)
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {

        /**
         * 保存库存工作单的详情
         */
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        orderTaskService.save(taskEntity);


        //1、按照下单的收获地址，找到一个就近仓库，锁定库存

        //1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品哪有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());
        //Boolean allLock = true;
        //2、锁定库存
        for (SkuWareHasStock stock : collect) {
            Boolean skuStocked = false;
            Long skuId = stock.getSkuId();
            List<Long> wareIds = stock.getWareId();
            if (wareIds==null||wareIds.size()==0){
                //没有仓库有任何库存
                throw new NoStockException(skuId);
            }else {
                for (Long wareId : wareIds) {
                    //成功就返回1 否则0
                    Long count = wareSkuDao.lockSkuStock(skuId,wareId,stock.getNum());
                    if (count==1){
                        skuStocked = true;
                        //TODO 告诉MQ库存锁定成功
                        WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null,skuId,null,stock.getNum(),taskEntity.getId(),wareId,1);
                        orderTaskDetailService.save(taskDetailEntity);
                        StockLockedTo stockLockedTo = new StockLockedTo();
                        StockDetailTo stockDetailTo = new StockDetailTo();
                        BeanUtils.copyProperties(taskDetailEntity,stockDetailTo);
                        stockLockedTo.setId(taskEntity.getId());
                        //只发id不行 回滚数据
                        stockLockedTo.setDetail(stockDetailTo);
                        rabbitTemplate.convertAndSend("stock-event-exchange","stock.locked",stockLockedTo);
                        break;
                    }else{
                        //当前仓库锁失败，重试下一个仓库
                    }
                }
                if (skuStocked==false){
                    //当前商品所有仓库都没有锁住
                    throw new NoStockException(skuId);
                }
            }
        }
        //3、肯定全部锁定成功
        return true;
    }

    @Override
    public void unlockStock(StockLockedTo to) {
        System.out.println("收到解锁库存的消息");
        StockDetailTo detail = to.getDetail();
        Long detailId = detail.getId();
        /**
         * 1、查询数据库关于这个订单的锁定库存的信息
         * 有：证明库存锁定成功了
         *   解锁：订单情况
         *     1、没有这个订单 无需解锁
         *     2、有这个订单。
         *          订单状态：已取消：解锁库存
         *                   没取消：不能解锁
         * 没有：库存锁定失败了 库存回滚 无需解锁
         */
        WareOrderTaskDetailEntity byId = orderTaskDetailService.getById(detailId);
        if (byId!=null){
            //解锁
            Long id = to.getId();
            //查到订单信息
            WareOrderTaskEntity taskEntity = orderTaskService.getById(id);
            //通过订单信息得到订单号
            String orderSn = taskEntity.getOrderSn();
            //根据订单号 查询订单状态
            R r = orderFeignService.getOrderStatus(orderSn);
            if (r.getCode()==0){
                //订单数据返回成功
                OrderVo data = r.getData(new TypeReference<OrderVo>() {
                });
                //订单不存在
                //判断订单状态 4:订单已被取消了
                if (data==null||data.getStatus() == 4 ){
                    if(byId.getLockStatus()==1){
                        //解锁
                        unLockStock(detail.getSkuId(),detail.getWareId(),detail.getSkuNum(),detailId);
                    }

                }
            }else{
                //消息拒绝后 重新放到队列中 让别人继续消费解锁
                throw new RuntimeException("远程服务失败");
            }
        }else{
            //无需解锁
        }
    }

    //防止订单服务卡顿 导致订单消息一直改不了，库存消息优先到期，
    @Transactional
    @Override
    public void unlockStock(OrderTo to) {
        String orderSn = to.getOrderSn();
        //查一下最新的订单状态,防止重复解锁库存//R r = orderFeignService.getOrderStatus(orderSn);
        WareOrderTaskEntity taskEntity = orderTaskService.getOrderTaskByOrderSn(orderSn);
        Long id = taskEntity.getId();
        //按照工资单 找到所有没有解锁的库存 进行解锁
        List<WareOrderTaskDetailEntity> entities = orderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity entity : entities) {
            unLockStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum(),entity.getTaskId());
        }

    }

    @Data
    class SkuWareHasStock{
        private Long skuId;//当前商品的id
        private Integer num; //锁多少件
        private List<Long> wareId;//都在哪些仓库有库存
    }


}